package com.bigboss.knowstar.controller;

import com.bigboss.knowstar.entity.Homework;
import com.bigboss.knowstar.entity.model.APIResult;
import com.bigboss.knowstar.exception.HomeworkException;
import com.bigboss.knowstar.service.impl.HomeworkServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Map;

import static com.bigboss.knowstar.utils.ValidateData.validateData;

@RestController
@RequestMapping("/homework")
public class HomeworkController {
    
    @Autowired
    private HomeworkServiceImpl homeworkService;

    @PostMapping("/{ClassId}")
    public APIResult homeworkCreate(@PathVariable Integer ClassId, @RequestBody @Validated Homework homework, BindingResult result) {
        try {
            ArrayList<String> data = validateData(result);
            if (data != null) {
                return APIResult.error(data);
            }
            homeworkService.createHomework(ClassId, homework);
            return APIResult.success("作业创建成功");
        } catch (HomeworkException e) {
            return APIResult.error("作业创建失败:" + e.getMessage());
        }
    }

    @PutMapping("/{Hid}")
    public APIResult homeworkUpdate(@PathVariable Integer Hid, @RequestBody Map<String, Object> fields) {
        try {
            homeworkService.updateHomework(Hid, fields);
            return APIResult.success("作业更新成功");
        } catch (HomeworkException e) {
            return APIResult.error("作业更新失败:" + e.getMessage());
        }
    }

    @DeleteMapping("/{Hid}")
    public APIResult homeworkDelete(@PathVariable Integer Hid) {
        try {
            homeworkService.deleteHomework(Hid);
            return APIResult.success("作业删除成功");
        } catch (HomeworkException e) {
            return APIResult.error("作业删除失败:" + e.getMessage());
        }
    }

    @GetMapping("/{Hid}")
    public APIResult homeworkQueryByFid(@PathVariable Integer Hid) {
        try {
            Homework homework = homeworkService.getHomework(Hid);
            return APIResult.success(homework);
        } catch (HomeworkException e) {
            return APIResult.error("作业查询失败:" + e.getMessage());
        }
    }
}
